import {
  ProCard,
  ProTable,
  ProForm,
  ModalForm,
  ProFormRadio,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { message, Image, Tag } from 'antd';
import { useEffect, useState } from 'react';
import { checkOrder, getExceptionOrderDetail } from '../service';
import { ExceptionOrderDetail, LastSensorItem } from '../types.d';
import styles from '../style.less';
import PatrolImage from './PatrolImages';
import { useModel } from 'umi';
import { Auths } from '@/utils/types.d';
import * as moment from 'moment';

const fallbackImg =
  '';

const mapExpectionStatus = (type: number) => {
  switch (type) {
    case 1:
      return '车牌冲突';
    case 2:
      return '车牌变更';
    case 3:
      return '地磁有车，巡检无车';
    case 4:
      return '地磁无车，巡检有车';
    default:
      return '未知异常';
  }
};
const mapExceptionStatusToOptions = (type: number) => {
  switch (type) {
    case 1:
      return [
        {
          label: '关联订单正确',
          value: 1,
        },
        {
          label: '当前订单正确',
          value: 2,
        },
      ];
    case 2:
      return [
        {
          label: '车牌未变更',
          value: 1,
        },
        {
          label: '车牌变更',
          value: 2,
        },
      ];
    default:
      return [
        {
          label: '地磁数据正确',
          value: 1,
        },
        {
          label: '巡检数据正确',
          value: 2,
        },
      ];
  }
};

const DetailModal = (props: {
  id: string;
  visible: boolean;
  close: () => void;
  reload: () => void;
}) => {
  const { initialState } = useModel('@@initialState');
  const { id, visible, close, reload } = props;
  const [currOrder, setCurrOrder] = useState<ExceptionOrderDetail>();
  const [imageVisible, setImageVisible] = useState<boolean>(false);
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.abnormalOrder || []) : new Set();
  const ifModify = auths.has(Auths.MODIFY);
  const refreshOrder = () => {
    getExceptionOrderDetail(id).then((res) => {
      if (res?.success) {
        setCurrOrder(res.data);
        return;
      } else {
        message.error({ key: 'exception_detail', content: res?.message || '获取失败' });
        return;
      }
    });
  };
  useEffect(() => {
    getExceptionOrderDetail(id).then((res) => {
      if (res?.success) {
        setCurrOrder(res.data);
        return;
      } else {
        message.error({ key: 'exception_detail', content: res?.message || '获取失败' });
      }
    });
  }, [id]);
  return (
    <ModalForm
      width="90vw"
      style={{
        minWidth: '1000px',
      }}
      title="异常订单审核"
      submitter={false}
      visible={visible}
      modalProps={{ destroyOnClose: true, maskClosable: false, onCancel: close }}
    >
      {currOrder && (
        <ProCard headStyle={{ padding: 0, margin: 0 }} bodyStyle={{ padding: 0 }}>
          <ProCard colSpan={16} direction="column">
            <div style={{ textAlign: 'center', paddingBottom: '10px' }}>
              <Image
                height="30vh"
                preview={{ visible: false }}
                src={currOrder.patrolImages?.composeImageUrl}
                fallback={fallbackImg}
                onClick={() => setImageVisible(true)}
              />
              <div style={{ display: 'none' }}>
                <Image.PreviewGroup
                  preview={{
                    visible: imageVisible,
                    onVisibleChange: (vis) => setImageVisible(vis),
                  }}
                >
                  {currOrder.patrolImages?.composeImageUrl && (
                    <Image height="50vh" src={currOrder.patrolImages?.composeImageUrl} />
                  )}
                  {currOrder.patrolImages?.eventImageUrl && (
                    <Image height="50vh" src={currOrder.patrolImages?.eventImageUrl} />
                  )}
                  {currOrder.patrolImages?.plateImageUrl && (
                    <Image height="50vh" src={currOrder.patrolImages?.plateImageUrl} />
                  )}
                </Image.PreviewGroup>
              </div>
            </div>
            <ProCard ghost>
              <ProCard
                ghost
                title="历史巡检数据"
                bodyStyle={{
                  display: 'flex',
                }}
              >
                {currOrder?.lastPatrols?.map((item) => (
                  <PatrolImage item={item} />
                ))}
              </ProCard>
              <ProCard ghost title="历史地磁数据">
                <ProTable<LastSensorItem>
                  search={false}
                  toolBarRender={false}
                  columns={[
                    {
                      title: '_id',
                      dataIndex: '_id',
                      hideInTable: true,
                      hideInForm: true,
                      hideInSearch: true,
                    },
                    {
                      title: '设备编号',
                      dataIndex: 'deviceSn',
                      hideInSearch: true,
                      hideInForm: true,
                      align: 'center',
                    },
                    {
                      title: '上报时间',
                      dataIndex: 'revicedTime',
                      hideInSearch: true,
                      hideInForm: true,
                      align: 'center',
                      valueType: 'dateTime',
                    },
                    {
                      title: '地磁状态',
                      dataIndex: 'status',
                      hideInSearch: true,
                      hideInForm: true,
                      align: 'center',
                      valueEnum: {
                        0: { text: <Tag color="success">车辆驶出</Tag> },
                        1: { text: <Tag color="error">车辆驶入</Tag> },
                        2: { text: <Tag color="success">持续空闲</Tag> },
                        3: { text: <Tag color="error">持续占用</Tag> },
                        98: { text: <Tag color="error">设备故障</Tag> },
                      },
                    },
                  ]}
                  pagination={false}
                  rowKey="_id"
                  dataSource={currOrder?.lastSensors || []}
                />
              </ProCard>
            </ProCard>
          </ProCard>
          <ProCard colSpan={8}>
            <table
              style={{ marginTop: 10 }}
              cellSpacing={0}
              cellPadding={0}
              className={styles.mytable}
            >
              <tbody>
                <tr>
                  <td>地磁状态：</td>
                  <td>泊位地磁状态</td>
                </tr>
                <tr>
                  <td>地磁状态变化时间：</td>
                  <td>2012516152</td>
                </tr>
                <tr>
                  <td>泊位编号：</td>
                  <td>{currOrder.spotId}</td>
                </tr>
                <tr>
                  <td>异常类型：</td>
                  <td>{mapExpectionStatus(currOrder.type)}</td>
                </tr>
                <tr>
                  <td>车牌号码：</td>
                  <td>{currOrder.plateNumber}</td>
                </tr>
              </tbody>
            </table>
            {currOrder.status != 1 && (
              <>
                <h4 style={{ marginTop: 10 }}>审单结果</h4>
                <table cellSpacing={0} cellPadding={0} className={styles.mytable}>
                  <tbody>
                    <tr>
                      <td>处理结果：</td>
                      <td>
                        {currOrder.correctType == 1 ? '保持原数据不变' : '依照巡检结果更新订单'}
                      </td>
                    </tr>
                    <tr>
                      <td>处理时间：</td>
                      <td>{moment(currOrder.handleTime).format('YYYY-MM-DD HH:mm:ss')}</td>
                    </tr>
                    <tr>
                      <td>备注说明：</td>
                      <td>{currOrder.remark}</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}
            {ifModify && currOrder.status == 1 && (
              <ProForm<{
                correctType: number;
                remark: string;
              }>
                style={{
                  marginTop: '20px',
                  width: '100%',
                }}
                layout="horizontal"
                submitter={{
                  resetButtonProps: {
                    style: {
                      display: 'none',
                    },
                  },
                  submitButtonProps: {},
                  render: (p, ds) => <div style={{ width: '100%', textAlign: 'right' }}>{ds}</div>,
                }}
                onFinish={async (values) => {
                  const res = await checkOrder(id, values);
                  if (!res.success) {
                    message.error({ content: res.message || '审核失败', key: 'check_order' });
                    return false;
                  }
                  message.success({ content: res.message || '', key: 'check_order' });
                  refreshOrder();
                  reload();
                  return true;
                }}
              >
                <ProFormRadio.Group
                  label="审核结果"
                  name="correctType"
                  initialValue={1}
                  options={mapExceptionStatusToOptions(currOrder.type)}
                />
                <ProFormTextArea width="lg" label="审单备注" name="remark" />
              </ProForm>
            )}
          </ProCard>
        </ProCard>
      )}
    </ModalForm>
  );
};

export default DetailModal;
